<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>

<!DOCTYPE html>
<html lang="UTF-8">

<head>
    <jsp:include page="header.jsp"></jsp:include>
    <link rel="stylesheet" href="css/pagination.css"/>
    <script type="text/javascript" src="script/jquery.pagination.js"></script>
    <link rel="stylesheet" href="ztree/zTreeStyle.css"/>
    <script type="text/javascript" src="ztree/jquery.ztree.all-3.5.min.js"></script>
</head>
<body>
<jsp:include page="nav.jsp"/>


<div class="container-fluid">
    <div class="row">

        <jsp:include page="sidebar.jsp"/>

        <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">


            <div class="panel panel-default">
                <div class="panel-heading">
                    <h3 class="panel-title"><i class="glyphicon glyphicon-th"></i> 数据列表</h3>
                </div>
                <div class="panel-body">

                    <form class="form-inline" role="form" style="float:left;">
                        <div class="form-group has-feedback">
                            <div class="input-group">
                                <div class="input-group-addon">查询条件</div>
                                <input class="form-control has-success" type="text" id="keywordInput"
                                       placeholder="请输入查询条件">
                            </div>
                        </div>
                        <button type="button" class="btn btn-warning" id="searchBtn"><i
                                class="glyphicon glyphicon-search"></i> 查询
                        </button>
                    </form>

                    <button type="button" class="btn btn-danger" style="float:right;margin-left:10px;"
                            id="batchRemoveBtn"><i
                            class=" glyphicon glyphicon-remove"></i> 删除
                    </button>
                    <button id="addBtn" type="button" class="btn btn-primary"
                            style="float: right;">
                        <i class="glyphicon glyphicon-plus"></i> 新增
                    </button>
                    <br>
                    <hr style="clear:both;">
                    <div class="table-responsive">
                        <table class="table  table-bordered">
                            <thead>
                            <tr>
                                <th width="30">#</th>
                                <th width="30"><input id="summaryBox" type="checkbox"></th>
                                <th>名称</th>
                                <th width="100">操作</th>
                            </tr>
                            </thead>


                            <tbody id="roleTableBody">
                            <%--<tr>
                                <td>1</td>
                                <td><input type="checkbox"></td>
                                <td>PM - 项目经理</td>
                                <td>
                                    <button type="button" class="btn btn-success btn-xs"><i
                                            class=" glyphicon glyphicon-check"></i></button>
                                    <button type="button" class="btn btn-primary btn-xs"><i
                                            class=" glyphicon glyphicon-pencil"></i></button>
                                    <button type="button" class="btn btn-danger btn-xs"><i
                                            class=" glyphicon glyphicon-remove"></i></button>
                                </td>
                            </tr>--%>
                            </tbody>


                            <tfoot>
                            <tr>
                                <td colspan="6" align="center">
                                    <div id="Pagination" class="pagination">
                                        <!-- 这里显示分页 -->
                                    </div>
                                </td>
                            </tr>
                            </tfoot>

                        </table>
                    </div>
                </div>
            </div>


        </div>

        <script>
            $(function () {
                console.log("----<进来了")
                //初始化全局参数
                initGlobalVariable();
                //获取分页数据
                showPage();

            });
            //全选按钮
            $("#summaryBox").click(function () {

                var currentStatus = this.checked;
                layer.msg("dddds" + currentStatus)
                $(".itemBox").prop("checked", currentStatus)
            })
            //批量删除按钮
            $("#batchRemoveBtn").click(function () {

                //1 先获取选中的ids
                // var ids = $(".itemBox:checked").attr("roleid")
                var checkedLength = $(".itemBox:checked").length
                if (checkedLength == 0) {
                    layer.msg("请至少选中一条")
                    return
                }
                window.roleIdArray = new Array();
                $(".itemBox:checked").each(function () {
                    var roleId = $(this).attr("roleid")
                    window.roleIdArray.push(roleId);
                })

                //2 把这些要删除的role 查出来然后显示


                // 调用函数打开模态框
                showRemoveConfirmModal();

            })

            // 根据roleIdArray查询roleList
            function getRoleListByRoleIdArray(roleIdArray) {

                // 1.将roleIdArray转换成JSON字符串
                var requestBody = JSON.stringify(roleIdArray);

                // 2.发送Ajax请求
                var ajaxResult = $.ajax({
                    "url": "role/get/list/by/id/list.json",
                    "type": "post",
                    "data": requestBody,
                    "contentType": "application/json;charset=UTF-8",
                    "dataType": "json",
                    "async": false
                });

                // 3.获取JSON对象类型的响应体
                var resultEntity = ajaxResult.responseJSON;

                // 4.验证是否成功
                var result = resultEntity.result;

                if (result == "SUCCESS") {

                    // 5.如果成功，则返回roleList
                    return resultEntity.data;
                }

                if (result == "FAILED") {
                    layer.msg(resultEntity.message);
                    return null;
                }

                return null;

            }

            // 调用函数打开模态框
            function showRemoveConfirmModal() {

                // 1.将模态框显示出来
                $("#confirmModal").modal("show");

                // 2.根据roleIdList获取roleList
                var roleList = getRoleListByRoleIdArray(window.roleIdArray);

                // 3.清空#confirmModalTableBody
                $("#confirmModalTableBody").empty();

                // 4.填充#confirmModalTableBody
                for (var i = 0; i < roleList.length; i++) {

                    // 5.获取角色相关数据
                    var role = roleList[i];

                    var id = role.id;

                    var name = role.name;

                    var trHTML = "<tr><td>" + id + "</td><td>" + name + "</td></tr>";

                    // 6.执行填充
                    $("#confirmModalTableBody").append(trHTML);
                }

                //给模态框的确认按钮添加事件
                $("#confirmModalBtn").click(function () {
                    //执行批量删除操作
                    $.ajax(
                        {
                            "url": "role/batch/remove.json",
                            "type": "post",
                            "data": JSON.stringify(window.roleIdArray),
                            "contentType": "application/json;charset=UTF-8",
                            "dataType": "json",
                            "success": function (response) {

                                // 不管成功还是失败，都需要关掉模态框
                                $("#confirmModal").modal("hide");

                                var result = response.result;

                                if (result == "SUCCESS") {
                                    layer.msg("操作成功！");
                                    // 如果删除成功，则重新调用分页方法
                                    showPage();
                                }

                                if (result == "FAILED") {
                                    layer.msg(response.message);
                                }


                            },
                            "error": function (response) {
                                layer.msg(response.message)
                            },
                        }
                    )

                });

            }


            //按条件查询
            $("#searchBtn").click(function () {
                var keywords = $.trim($("#keywordInput").val());
                if (keywords == null || keywords == "") {
                    layer.msg("请输入查询条件")
                    return;
                }
                window.keyword = keywords;
                showPage();

            })

            function initGlobalVariable() {
                window.pageSize = 5;
                window.pageNum = 1;
                window.keyword = "";
            }


            function showPage() {
                //获取pageinfo
                var pageInfo = getPageInfo();
                if (pageInfo == null) {
                    // 如果没有获取到pageInfo数据，则停止后续操作
                    return;
                }

                //向tbody填入数据
                generateTableBody(pageInfo)
                // 在页面上的表格中tfoot标签内显示分页的页码导航条
                initPagination2(pageInfo);
            }

            //3
            function initPagination2(pageInfo) {
                // 声明变量存储分页导航条显示时的属性设置
                var paginationProperties = {
                    num_edge_entries: 3,			//边缘页数
                    num_display_entries: 5,		//主体页数
                    callback: pageselectCallback2,	//回调函数
                    items_per_page: window.pageSize,	//每页显示数据数量，就是pageSize
                    current_page: (window.pageNum - 1),//当前页页码
                    prev_text: "上一页",			//上一页文本
                    next_text: "下一页"			//下一页文本
                };
                // 显示分页导航条
                $("#Pagination").pagination(pageInfo.total, paginationProperties);
            }

            function pageselectCallback2(pageIndex, jq) {
                // 将全局变量中的pageNum修改为最新值
                // pageIndex从0开始，pageNum从1开始
                window.pageNum = pageIndex + 1;
                // 调用分页函数重新执行分页
                showPage();
                return false;
            }

            //获取pageinfo
            function getPageInfo() {

                var ajaxResult = $.ajax({
                    "url": "role/search/by/keyword.json",
                    "type": "post",
                    "data": {
                        "pageNum": (window.pageNum == undefined) ? 1 : window.pageNum,
                        "pageSize": (window.pageSize == undefined) ? 5 : window.pageSize,
                        "keyword": window.keyword
                    },
                    "dataType": "json",
                    "async": false

                });

                console.log(ajaxResult)

                var responseJSONs = ajaxResult.responseJSON;
                if (responseJSONs.result == "SUCCESS") {
                    return responseJSONs.data;
                }
                if (responseJSONs.result == "FAILED") {
                    layer.msg(responseJSONs.message)
                    return null;
                }
                return null;
            }

            //填塞数据
            function generateTableBody(pageInfo) {

                if (pageInfo != null) {

                    $("#roleTableBody").empty()

                    var listJson = pageInfo.list;
                    if (listJson == null || listJson.length == 0) {
                        $("#roleTableBody").append("<tr><td colspan='4' style='text-align:center;'>没有查到数据</td></tr>")
                    }

                    for (var i = 0; i < listJson.length; i++) {
                        var role = listJson[i];
                        var checkBtn = "<button roleId='" + role.id + "' type='button' class='btn btn-success btn-xs checkBtn''><i class=' glyphicon glyphicon-check'></i></button>";
                        var pencilBtn = "<button  roleId='" + role.id + "' type='button' class='btn btn-primary btn-xs editBtn''><i class=' glyphicon glyphicon-pencil'></i></button>";
                        var removeBtn = "<button  roleId='" + role.id + "' type='button' class='btn btn-danger btn-xs  removeBtn'><i class=' glyphicon glyphicon-remove'></i></button>";

                        var numberTd = "<td>" + (i + 1) + "</td>";
                        var checkBoxTd = "<td><input   roleid='" + role.id + "' type='checkbox' class='itemBox'></td>";
                        var roleNameTd = "<td>" + role.name + "</td>";
                        var btnTd = "<td>" + checkBtn + " " + pencilBtn + " " + removeBtn + "</td>";

                        var tr = "<tr>" + numberTd + checkBoxTd + roleNameTd + btnTd + "</tr>";

                        // 将前面拼好的HTML代码追加到#roleTableBody中
                        $("#roleTableBody").append(tr);


                    }


                }

                //给角色分配资源按钮添加事件
                $("#roleTableBody").on("click", ".checkBtn", function () {

                    // 打开模态框
                    $("#roleAssignAuthModal").modal("show");

                    // 初始化模态框中显示的树形结构
                    // 1.创建setting对象
                    var setting = {
                        "data": {
                            "simpleData": {
                                "enable": true,
                                "pIdKey": "categoryId"
                            },
                            "key": {
                                "name": "title"
                            }
                        },
                        "check": {
                            "enable": true
                        }
                    };
                    // 2.获取JSON数据
                    var ajaxResult = $.ajax({
                        "url": "assign/get/all/auth.json",
                        "type": "post",
                        "dataType": "json",
                        "async": false
                    });

                    if (ajaxResult.responseJSON.result == "FAILED") {
                        layer.msg(ajaxResult.responseJSON.message);

                        return;
                    }

                    var zNodes = ajaxResult.responseJSON.data;

                    // 3.初始化树形结构
                    $.fn.zTree.init($("#treeDemo"), setting, zNodes);

                    window.roleId= $(this).attr("roleId")

                    var dd = {
                        "roleId": $(this).attr("roleId"),
                        "random": Math.random()
                    }

                    // 5.查询以前已经分配过的authId
                    var ajaxResult = $.ajax({
                        "url": "assign/get/assigned/auth/id/list.json",
                        "type": "post",
                        "data":dd,
                        "dataType": "json",
                        "async": false
                    });

                    if (ajaxResult.responseJSON.result == "FAILED") {
                        layer.msg(ajaxResult.responseJSON.message);
                        return;
                    }

                    var authIdList = ajaxResult.responseJSON.data;

                    // 6.使用authIdList勾选对应的树形节点
                    // ①遍历authIdList
                    for (var i = 0; i < authIdList.length; i++) {
                        // ②在遍历过程中获取每一个authId
                        var authId = authIdList[i];

                        // ③根据authId查询到一个具体的树形节点
                        // key：查询节点的属性名
                        // value：查询节点的属性值，这里使用authId
                        var key = "id";

                        var treeNode = $.fn.zTree.getZTreeObj("treeDemo").getNodeByParam(key, authId);

                        // ④勾选找到的节点
                        // treeNode：当前要勾选的节点
                        // true：表示设置为勾选状态
                        // false：表示不联动
                        $.fn.zTree.getZTreeObj("treeDemo").checkNode(treeNode, true, false);

                    }




                    //重新分派权限

                    $("#roleAssignAuthBtn").click(function(){

                        var authIdArray = new Array();

                        // 调用zTreeObj的方法获取当前已经被勾选的节点
                        var checkedNodes = $.fn.zTree.getZTreeObj("treeDemo").getCheckedNodes();

                        // 遍历checkedNodes
                        for(var i = 0; i < checkedNodes.length; i++) {

                            // 获取具体的一个节点
                            var node = checkedNodes[i];

                            // 获取当前节点的id属性
                            var authId = node.id;

                            // 将authId存入数组
                            authIdArray.push(authId);
                        }

                        // 在handler方法中使用@RequestBody接收
                        // 方便使用的数据类型是：@RequestBody Map<String, List<Integer>>
                        // {"roleIdList":[2],"authIdList":[2,3,5,7]}
                        // 封装要发送给handler的JSON数据
                        var requestBody = {"roleIdList":[window.roleId], "authIdList": authIdArray};

                        // 发送请求
                        var ajaxResult = $.ajax({
                            "url": "assign/do/assign.json",
                            "type": "post",
                            "data": JSON.stringify(requestBody),
                            "contentType": "application/json;charset=UTF-8",
                            "dataType": "json",
                            "async": false
                        });

                        if(ajaxResult.responseJSON.result == "SUCCESS") {

                            layer.msg("操作成功！");

                        }

                        if(ajaxResult.responseJSON.result == "FAILED") {

                            layer.msg(ajaxResult.responseJSON.message);

                        }

                        $("#roleAssignAuthModal").modal("hide");

                    });



                });




            }

            //单条删除
            $("#roleTableBody").on("click", ".removeBtn", function () {
                // 获取当前记录的roleId
                var roleId = $(this).attr("roleId");

                // layer.msg("roleid" + roleId)
                window.roleIdArray = new Array();

                window.roleIdArray.push(roleId);

                // 打开模态框（后续所有操作都和批量删除一样）
                showRemoveConfirmModal();

            });

            //新增
            $("#addBtn").click(function () {

                //打开添加模态框
                $("#addModal").modal("show")

                $("#addModalBtn").click(function () {

                    var roleName = $.trim($("#roleNameInput").val())
                    if (roleName == null || roleName == "") {
                        layer.msg("请输入有效角色名称！");
                        return;
                    }

                    // 2.发送请求
                    $.ajax({
                        "url": "role/save/role.json",
                        "type": "post",
                        "data": {
                            "roleName": roleName
                        },
                        "dataType": "json",
                        "success": function (response) {

                            var result = response.result;

                            if (result == "SUCCESS") {
                                layer.msg("操作成功！");

                                // 3.操作成功重新分页
                                // 前往最后一页
                                window.pageNum = 999999;
                                showPage();
                            }

                            if (result == "FAILED") {
                                layer.msg(response.message);
                            }

                            // 4.不管成功还是失败，关闭模态框
                            $("#addModal").modal("hide");

                            // 5.清理本次在文本框填写的数据
                            $("#roleNameInput").val("");

                        },
                        "error": function (response) {
                            layer.msg(response.message);
                        }
                    });

                })
            });

            //修改

            $("#roleTableBody").on("click", ".editBtn", function () {
                // 1.获取当前按钮的roleId
                window.roleId = $(this).attr("roleId");
                // 2.获取当前按钮所在行的roleName
                var roleName = $(this).parents("tr").children("td:eq(2)").text();
                // 3.修改模态框中文本框的value值，目的是在显示roleName
                $("#roleNameInputEdit").val(roleName);
                // 4.打开模态框
                $("#editModal").modal("show");

                $("#editModalBtn").click(function () {

                    layer.msg("pp:" + window.roleId)

                    // 1.获取文本框值
                    var roleName = $.trim($("#roleNameInputEdit").val());

                    if (roleName == null || roleName == "") {
                        layer.msg("请输入有效角色名称！");

                        return;
                    }

                    console.log(roleName + "::" + window.roleId)

                    var id = window.roleId;

                    // 2.发送请求
                    $.ajax({
                        "url": "role/update/role.json",
                        "type": "post",
                        "data": {
                            "id": id,
                            "name": roleName
                        },
                        "dataType": "json",
                        "async": false,
                        "contentType": "application/x-www-form-urlencoded",
                        "success": function (response) {
                            var result = response.result;

                            if (result == "SUCCESS") {
                                layer.msg("操作成功！");

                                // 3.操作成功重新分页
                                showPage();
                            }

                            if (result == "FAILED") {
                                layer.msg(response.message);
                            }

                            // 4.不管成功还是失败，关闭模态框
                            $("#editModal").modal("hide");

                        }
                    })
                });


            });


        </script>
    </div>
</div>


<%@ include file="/WEB-INF/include-modal-role-confirm.jsp" %>
<%@ include file="/WEB-INF/include-modal-role-add.jsp" %>
<%@ include file="/WEB-INF/include-modal-role-edit.jsp" %>
<%@ include file="/WEB-INF/include-modal-assign-auth.jsp" %>
</body>
</html>
